Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
Django models.Manager custom SQL query "more than one row returned" error

So I'm trying to get the result of the age() function on PostgreSQL from a column in the DB.

The goal is to append a new virtual column with the age or time elapsed since the datetime stored the database.

I tried this by creating a models.Manager in Django to add this new column:

class PriorityManager(models.Manager):
    def get_queryset(self):
        time_elapsed = RawSQL('SELECT EXTRACT(EPOCH FROM age(datetime)) AS age FROM backend_post',
                               params=(),
                               output_field=models.IntegerField())
    return super(PriorityManager, self).get_queryset().annotate(score=time_elapsed)

I need a score column to help sort the objects later, and the score is based on the time elapsed.

The query SELECT EXTRACT(EPOCH FROM age(datetime)) AS age FROM backend_post; works in the dbshell but when running it on Django, the following message comes up:

ProgrammingError at /api/post/list/ more than one row returned by a subquery used as an expression

I suspect the problem is that the query returns a whole column of elements while the models.Manager expected only one result. I believe there should be something sent as a parameter in the RawSQL query but I couldn't figure out what it is...

Anyone knows what to do?

Thank you very much!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Solved this problem by using

http://django-postgres-stats.readthedocs.io/

It allows for many custom postgres functions with django, just what I needed. Don't know why it took me so long to find it!

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!